package com.i8office.android.zhihuixinwu.util;

import android.text.TextUtils;

import com.cyan.tools.callback.RequestCallback;
import com.i8office.android.zhihuixinwu.bean.Code;
import com.i8office.android.zhihuixinwu.bean.Result;
import com.socks.library.KLog;

import io.reactivex.observers.DisposableObserver;

/**
 * Created by pc on 2018/7/7.
 */

public class OfficeSubscriber<T> extends DisposableObserver<T> {
    private RequestCallback requestCallback;

    public OfficeSubscriber(RequestCallback requestCallback) {
        this.requestCallback = requestCallback;
    }

    @Override
    protected void onStart() {
        super.onStart();
        requestCallback.beforeRequest();
    }

    @Override
    public void onComplete() {
        requestCallback.requestComplete();
        dispose();
    }

    @Override
    public void onError(Throwable e) {
        KLog.e(e == null ? "Throwable is null" : e.toString());
        requestCallback.requestError("服务器异常");
        dispose();
    }

    @Override
    public void onNext(T o) {
        if (o == null) {
            requestCallback.requestError("服务器异常");
            return;
        }
        if (o instanceof Result) {
            Result result = (Result) o;
            if (!TextUtils.isEmpty(result.getMessage())) {
                requestCallback.requestError(result.getMessage());
            } else {
                requestCallback.requestSuccess(result.getData());
            }
        } else if (o instanceof Code) {
            Code c = (Code) o;
            if (c.isSucceed()) {
                requestCallback.requestSuccess(o);
            } else {
                if (!TextUtils.isEmpty(c.getMessage())) {
                    requestCallback.requestError(c.getMessage());
                }
            }
        } else {
            requestCallback.requestSuccess(o);
        }
    }
}
